package com.spark.data

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.shizhefei.view.indicator.IndicatorViewPager
import com.spark.common.BaseFragment
import com.spark.common.helper.TabBarTextListener
import com.spark.common.widget.BadgeTextView
import kotlinx.android.synthetic.main.frag_borrow_list.*

/**
 * 借阅清单
 */
class BorrowListFragment : BaseFragment() {
    companion object {
        fun newInstance(): BorrowListFragment {
            val fragment = BorrowListFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_borrow_list
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        iv_back.setOnClickListener { pop() }
    }

    override fun onEnterAnimationEnd(savedInstanceState: Bundle?) {
        super.onEnterAnimationEnd(savedInstanceState)
        initPager()
    }

    fun initPager() {
        activity?.apply {
            tab.onTransitionListener = TabBarTextListener().setColorId(this, R.color.tab_selected_color, R.color.tab_normal_color)
            val vp = IndicatorViewPager(tab, pager)

            val borrowListAdapter = BorrowListAdapter(supportFragmentManager)
            vp.adapter = borrowListAdapter

            pager.isCanScroll = true
        }
    }
}

class BorrowListAdapter(fm: FragmentManager) : IndicatorViewPager.IndicatorFragmentPagerAdapter(fm) {
    private val tabNames = arrayOf("已通过", "审核中", "已结束")
    override fun getViewForTab(position: Int, convertView: View?, container: ViewGroup?): View? {
        var converter = convertView
        if (converter == null) converter = LayoutInflater.from(container?.context).inflate(R.layout.tab_item, container, false)
        val badgeText = converter?.findViewById<BadgeTextView>(R.id.tab_text)
        badgeText?.apply {
            text = tabNames[position]
            setTextSize(TypedValue.COMPLEX_UNIT_SP, 14F)
        }
        return converter
    }

    override fun getFragmentForPage(position: Int): Fragment {
        return BorrowChildFragment.newInstance(position)
    }

    override fun getCount(): Int {
        return tabNames.size
    }

}